package com.rc.saas.tenant.service.order;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.mq.MqConfig;
import com.rc.saas.tenant.common.mq.MqProducer;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseMemberMapper;
import com.rc.saas.tenant.mapper.member.*;
import com.rc.saas.tenant.mapper.order.OrderDiscountRecordMapper;
import com.rc.saas.tenant.mapper.order.OrderInfoMapper;
import com.rc.saas.tenant.mapper.order.OrderRefundApplyMapper;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.member.*;
import com.rc.saas.tenant.model.order.OrderDiscountRecord;
import com.rc.saas.tenant.model.order.OrderDiscountRecordExample;
import com.rc.saas.tenant.model.order.OrderInfo;
import com.rc.saas.tenant.model.order.OrderRefundApply;
import com.rc.saas.tenant.model.rc.RcOperatorAccountRecord;
import com.rc.saas.tenant.model.ticket.MemberTicket;
import com.rc.saas.tenant.search.order.OrderRefundApplySearch;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.finance.RcOperatorAccountRecordService;
import com.rc.saas.tenant.service.ticket.MemberTicketService;
import com.rc.saas.tenant.vo.order.ChargeStatisticsResult;
import com.rc.saas.tenant.vo.order.OrderRefundApplyVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class OrderRefundApplyServiceImpl implements OrderRefundApplyService {
    @Autowired
    private static Logger logger = LoggerFactory.getLogger(OrderRefundApplyServiceImpl.class);

    @Autowired
    private OrderRefundApplyMapper orderRefundApplyMapper;

    @Autowired
    private MemberAccountMapper memberAccountMapper;

    @Autowired
    private RcMemberFlagMapper rcMemberFlagMapper;

    @Autowired
    private EnterpriseMemberMapper enterpriseMemberMapper;

    @Autowired
    private MemberTicketService memberTicketService;

    @Autowired
    private MemberInfoMapper memberInfoMapper;


    @Autowired
    private RcOperatorAccountRecordService rcOperatorAccountRecordService;

    @Autowired
    private MemberAccountRecordMapper memberAccountRecordMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private OrderDiscountRecordMapper orderDiscountRecordMapper;

    @Autowired
    private RcMemberGainSettingMapper memberGainSettingMapper;


    @Override
    public OrderRefundApplyMapper getMapper() {
        return orderRefundApplyMapper;
    }

    @Override
    public PageInfo<OrderRefundApplyVo> listOrderRefund(OrderRefundApplySearch orderRefundApplySearch) {
        PageHelper.startPage(orderRefundApplySearch.getOffset(), orderRefundApplySearch.getLimit());
        List<OrderRefundApplyVo> orderList = orderRefundApplyMapper.listOrderRefund(orderRefundApplySearch);
        return new PageInfo<OrderRefundApplyVo>(orderList);
    }

    @Override
    public List<ChargeStatisticsResult> listRefundStatistics(List<Long> idList) {
        return orderRefundApplyMapper.listRefundStatistics(idList);
    }

    @Override
    public int updateStatus(Long orderRefundApplyId, String status, String remark) {

        //更新申请状态
        OrderRefundApply orderRefundApply = orderRefundApplyMapper.selectByPrimaryKey(orderRefundApplyId);
        orderRefundApply.setStatus(status);
        orderRefundApply.setRemark(remark);
        orderRefundApply.setRefundTime(new Date());
        orderRefundApply.setAuditingTime(new Date());
        orderRefundApplyMapper.updateByPrimaryKeySelective(orderRefundApply);

        //更新订单状态
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderRefundApply.getOrderId());

        MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(orderRefundApply.getMemberId());
        //更新权益状态
        RcMemberFlag rcMemberFlag = rcMemberFlagMapper.selectByPrimaryKey(orderRefundApply.getMemberId());
//        if (rcMemberFlag.getMemberLevel() == null) {
//            return 1;
//        }

        //memberAcountRecord 退款记录
        MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
        memberAccountRecord.setTenantCode(memberAccount.getTenantCode());
        memberAccountRecord.setMemberId(memberAccount.getMemberId());
        memberAccountRecord.setLocalTradeNo(orderRefundApply.getOrderNum());
        memberAccountRecord.setInTradeNo(orderRefundApply.getOrderNum());
        //支付的账户类型 0个人钱包 1 企业钱包 2权益金 3收益金
        memberAccountRecord.setAccountType(orderInfo.getAccountType());
        //记录类型(0会员在线充值,1支出,2转账收入,3分配余额,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移 13共享额度变更 14后台退款 15.原路退款 16原路返还 ) 17.先付后退充值 18.先付后退退款
        memberAccountRecord.setRecordType("14");
        //本次变更金额
        memberAccountRecord.setAmount(orderRefundApply.getAmount());
        memberAccountRecord.setResult(memberAccount.getAccount());
        memberAccountRecord.setRemark("退款");
        memberAccountRecord.setCreatedTime(new Date());
        memberAccountRecord.setLastUpdatedTime(new Date());
        if ("2".equals(status)) {
            //退款失败
            memberAccountRecord.setRefundStatus("3");
            return 1;
        } else {
            //退款成功
            memberAccountRecord.setRefundStatus("2");

        }
        memberAccountRecordMapper.insertSelective(memberAccountRecord);

        //更新订单
        orderInfo.setOrderRefundApplyId(orderRefundApplyId);
        orderInfo.setLastUpdatedTime(new Date());
        orderInfoMapper.updateByPrimaryKey(orderInfo);


        if ("0".equals(orderInfo.getAccountType())) {
            //更新余额
            memberAccount.setGiveAccount(BigDecimal.ZERO);
            memberAccount.setFrozenGiveAccount(BigDecimal.ZERO);
            memberAccount.setAccount(memberAccount.getAccount().add(orderRefundApply.getFactAmount()));
            memberAccountMapper.updateByPrimaryKey(memberAccount);

//            RcMemberGainSettingExample gainSettingExample = new RcMemberGainSettingExample();
//            gainSettingExample.createCriteria().andLevelSubEqualTo(rcMemberFlag.getSubLevel()).andGainTypeNotEqualTo("2")
//                    .andStatusEqualTo("0");
//            List<RcMemberGainSetting> settings = memberGainSettingMapper.selectByExample(gainSettingExample);
//            RcMemberGainSetting settingInfo = null;
//            for (int i = 0; i < settings.size(); i++) {
//                if (StringUtils.equals("1", settings.get(i).getIsDefault())) {
//                    settingInfo = settings.get(i);
//                    break;
//                } else {
//                    settingInfo = settings.get(i);
//                }
//            }
//            MemberAccountRecordExample recordExample = new MemberAccountRecordExample();
//            recordExample.createCriteria().andMemberIdEqualTo(orderRefundApply.getMemberId())
//                    .andRefundStatusEqualTo("2");
//            List<MemberAccountRecord> records = memberAccountRecordMapper.selectByExample(recordExample);
//            if (settingInfo != null) {
//                if (StringUtils.equals("0", settingInfo.getGainType())) {//代表充值送
//                    if (settingInfo.getRefundCountTarget() != null && settingInfo.getRefundCountTarget() <= records.size()) {//已满足退款次数无则扣
//                        rcMemberFlag.setGiveStatus("1");//停用则扣
//                    }
//                } else { //代表赠送金额
//                    if (settingInfo.getRefundUnhandsel() != null && settingInfo.getRefundUnhandsel() <= records.size()) {//已满足退款次数无赠送金额
//                        rcMemberFlag.setGiveStatus("1");//停用赠送金额
//                    }
//                }
//            }
//            //更新会员权益
//            rcMemberFlag.setMemberLevel("V0");
//            rcMemberFlag.setSubLevel("V0-1");
//            rcMemberFlagMapper.updateByPrimaryKeySelective(rcMemberFlag);


        } else {
            EnterpriseMember enterpriseMember = enterpriseMemberMapper.selectByPrimaryKey(rcMemberFlag.getEnterpriseId());
                    //enterpriseMemberMapper.selectMemberByMemberId(rcMemberFlag.getEnterpriseId());
            if (enterpriseMember==null){
                return 0;
            }
            enterpriseMember.setEnterpriseAccount(enterpriseMember.getEnterpriseAccount().add(orderRefundApply.getFactAmount()));
            //企业钱包，退款至企业账户
            enterpriseMemberMapper.updateByPrimaryKeySelective(enterpriseMember);

            //todo 更新企业退款状态


        }



        //退款优惠券
        OrderDiscountRecordExample discountRecordExample = new OrderDiscountRecordExample();
        discountRecordExample.createCriteria().andOrderIdEqualTo(orderInfo.getOrderId());
        List<OrderDiscountRecord> orderDiscountRecords = orderDiscountRecordMapper.selectByExample(discountRecordExample);
        for (OrderDiscountRecord orderDiscountRecord : orderDiscountRecords) {
            MemberTicket memberTicket = memberTicketService.selectByPrimaryKey(orderDiscountRecord.getDiscountId());
            if (Objects.isNull(memberTicket)) {
                continue;
            }
            memberTicket.setStatus("0");
            memberTicket.setUsedTime(null);
            memberTicket.setLastUpdatedTime(new Date());
            memberTicketService.updateByPrimaryKey(memberTicket);
        }


        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberAccount.getMemberId());

        //新增流水
        RcOperatorAccountRecord rcOperatorAccountRecord = new RcOperatorAccountRecord();
        rcOperatorAccountRecord.setRecordType("1");
        rcOperatorAccountRecord.setExplains("退款");
        rcOperatorAccountRecord.setAmount(orderRefundApply.getAmount());
        rcOperatorAccountRecord.setOrderNum(orderRefundApply.getOrderNum());
        rcOperatorAccountRecord.setRecordSource("0");
        rcOperatorAccountRecord.setEntryId(memberAccount.getMemberId());
        rcOperatorAccountRecord.setEntryName(memberInfo.getNickname());
        rcOperatorAccountRecord.setEntryType("1");
        rcOperatorAccountRecord.setEntryAccount(memberAccount.getAccount());
        rcOperatorAccountRecord.setOutId(memberAccount.getMemberId());
        rcOperatorAccountRecord.setOutName("平台");
        rcOperatorAccountRecord.setOutType("0");
        rcOperatorAccountRecord.setStatus("1");
        rcOperatorAccountRecord.setCreatedTime(new Date());
        rcOperatorAccountRecord.setLastUpdatedTime(new Date());
        rcOperatorAccountRecord.setRemark(remark);
        rcOperatorAccountRecordService.insertSelective(rcOperatorAccountRecord);

        return 1;
    }
}
